﻿using System;
using System.Windows.Forms;
using StationCommon;

namespace Station.Controls
{
    public partial class VehicleList : UserControl, IVehicleList
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.VehicleSaved += delegate { SetGridDataSource(); };
                SetGridDataSource();
            }
        }

        #endregion

        public VehicleList()
        {
            InitializeComponent();
            gridView.DoubleClick += gridView_DoubleClick;
        }

        #region Private Methods

        private void SetGridDataSource()
        {
            VeiculoDataSet dataSet = _controller.Vehicles();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.Veiculo.TableName;
        }
        
        private void ShowVehicle(string plate)
        {
            var window = new VehicleXtraForm {Plate = plate, Controller = _controller};
            window.ShowDialog();           
        }

        #endregion

        #region IVehicleList

        public void AddVehicle()
        {
            ShowVehicle("");
        }
        
        #endregion

        void gridView_DoubleClick(object sender, EventArgs e)
        {
            var vehicle = (VeiculoDataSet.VeiculoRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (vehicle == null)
                return;
            ShowVehicle(vehicle.Matricula);
        }
    }
}
